package top.lenjon.lib.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import top.lenjon.lib.mapper.AdminMapper;
import top.lenjon.lib.mapper.UserDetailMapper;
import top.lenjon.lib.model.LoginModel;
import top.lenjon.lib.service.LoginService;
import top.lenjon.lib.util.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Author whz
 * @Date 2020/11/8 22:52
 **/
@Service
@CacheConfig(cacheNames = "token")
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserDetailMapper userDetailMapper;

    @Autowired
    private AdminMapper adminMapper;


    @Override
    public String generateToken(LoginModel loginModel) {
        loginModel.setPassword("****");
        String token = UUID.randomUUID().toString().replace("-", "");
        redisUtil.set(token, loginModel, 30 * 60 * 60 * 24);
        return token;
    }

    @Override
    public boolean loginUser(LoginModel loginModel) {
        String name = loginModel.getUsername();
        String password = loginModel.getPassword();
        int type = loginModel.getType();
        String correctPwd;
        switch (type) {
            case 0:
                correctPwd = userDetailMapper.getPasswordByUsername(name);
                break;
            case 1:
            case 2:
                correctPwd = adminMapper.getPasswordByUsername(name);
                break;
            default:
                correctPwd = null;
        }
        return password.equals(correctPwd);

    }


    @Override
    public LoginModel checkToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        LoginModel userInfo = (LoginModel) redisUtil.get(token);
        return userInfo;
    }

    public String getToken(HttpServletRequest request) {
        return request.getHeader("token");
    }

    @Override
    public boolean logout(HttpServletRequest request) {
        String token = getToken(request);
        if (token != null) {
            redisUtil.del(token);
            return true;
        }
        return false;
    }

}
